var BillOfMaterial = function () {
  var template = /*html*/ `
    <div class="bill-of-material" v-loading.fullscreen.lock="loading">
      <div>
        <search-btn-view btn-text="查询物料清单" @before-open="resetSearch" @search="searchData">
          <template slot="append" v-if="orderInfo!==null&&orderInfo.canHandle">
            <el-button v-if="orderInfo.myApplyType!==1" size="medium" type="primary" @click="addMaterial">新增物料</el-button>
            <el-button v-if="orderInfo.hasApproval" size="medium" type="primary" @click="approvalOrder">
              审核订单
            </el-button>
            <!--<el-button size="medium" type="primary" @click="updateImage">更新订单图片</el-button>-->
          </template>
          <div slot="search-content">
            <common-search-form :search="search" request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:1,bom:1}"
              :search-field="searchField" label-width="100px" input-width="200px">
              <template slot="append">
                <el-form-item label="供方编号">
                  <el-input v-model="search.providerNo" style="width:200px" placeholder="请输入供方编号"></el-input>
                </el-form-item>
              </template>
            </common-search-form>
          </div>
        </search-btn-view>
      </div>
      <div class="bill-of-material-content" :class="{'hasPage':pagination.totalCount!==0}">
        <template v-if="materialList.length>0">
          <div class="colorDesc">
            <div>
              <div class="color" style="background:#F56C6C"></div>
              <div>红色标记代表物料已经删除</div>
            </div>
          </div>
          <div class="order-info clearfix" v-if="orderInfo!==null">
            <div v-if="orderInfo.orderId!==''">订单编号:{{orderInfo.orderId}}</div>
            <div v-if="orderInfo.companyOrderId!==''">公司订单编号:{{orderInfo.companyOrderId}}</div>
            <div v-if="orderInfo.factoryNo!==''">工厂型号:{{orderInfo.factoryNo}}</div>
            <div v-if="orderInfo.customerNo!==''">客户型号:{{orderInfo.customerNo}}</div>
          </div>
          <div class="bill-of-material-table-div">
            <el-table fit stripe border :data="materialList" style="width:100%" height="parent" :row-class-name="getMaterialTableClassName">
              <el-table-column v-if="orderInfo!==null&&orderInfo.canHandle&&orderInfo.myApplyType!==1" :resizable="false" label="操作" width="140px" fixed="left" align="center" key="handle">
                <template slot-scope="scope">
                  <template v-if="scope.row.type===0">
                    <el-button size="mini" type="primary" @click="toUpdateMaterial(scope.row)">修改</el-button>
                    <el-button size="mini" type="danger" @click="delMaterial(scope.row)">删除</el-button>
                  </template>
                </template>
              </el-table-column>
              <el-table-column :resizable="false" prop="lineNo" label="序号" width="45px" align="center" key="lineNo">
                <template slot-scope="scope">
                  <span>{{scope.row.lineNo==='-1'?globalConfig.orderDefaultRowIndex:scope.row.lineNo}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="materialCode" label="物料代码" min-width="180px" header-align="center" key="materialCode">
              </el-table-column>
              <el-table-column prop="materialType" label="物料类型" min-width="100px" header-align="center" :filters="materialTypeFilters" :filter-method="tableFilter" key="materialType">
              </el-table-column>
              <el-table-column prop="providerName" label="供应商" min-width="120px" header-align="center" key="materialCode">
              </el-table-column>
              <el-table-column prop="providerNo" label="供方编号" min-width="100px" header-align="center" key="materialCode">
              </el-table-column>
              <el-table-column prop="materialName" label="物料名称" min-width="120px" header-align="center" key="materialName">
              </el-table-column>
              <el-table-column prop="color" label="编号" min-width="120px" key="color" header-align="center"></el-table-column>
              <el-table-column prop="colorDescription" label="描述" min-width="120px" key="colorDescription" header-align="center">
              </el-table-column>
              <el-table-column prop="materialModel" label="规格型号" min-width="120px" key="materialModel" header-align="center">
              </el-table-column>
              <el-table-column prop="materialDeptName" label="物料部门" min-width="120px" key="materialDept" align="center">
              </el-table-column>
              <el-table-column label="仓位" min-width="100px" key="materialFactory" header-align="center">
                <template slot-scope="scope">
                  {{warehouseList[scope.row.materialFactory]}}
                </template>
              </el-table-column>
              <el-table-column prop="feedTotal" label="投料数" min-width="100px" key="feedTotal" align="center">
              </el-table-column>
              <el-table-column prop="yltsTotal" label="用料条数" min-width="100px" key="yltsTotal" align="center">
              </el-table-column>
              <el-table-column prop="orderTotal" label="订单数" min-width="80px" key="orderTotal" align="center">
              </el-table-column>
            </el-table>
          </div>
        </template>
        <template v-else>
          <div class="no-data">
            <div>没有搜索到匹配的物料清单</div>
          </div>
        </template>
      </div>
      <div style="margin-top:10px;text-align:right;" v-if="pagination.totalCount!==0">
        <el-pagination background :page-size="pagination.pageSize" :total="pagination.totalCount" :current-page.sync="pagination.currentPage"
          @current-change="pageChange"></el-pagination>
      </div>

      <el-dialog :title="formDialogTitle" :visible.sync="openMaterialForm" class="materialFormDialog" :fullscreen="true" @closed="materialDialogClosed">
        <bill-material-form v-if="openMaterialForm" :order="orderInfo" :mode="formMode" :dropdown-option="dropdownOption" :material="updateMaterial"
          @save-success="saveSuccess" @close-dialog="openMaterialForm=false"></bill-material-form>
      </el-dialog>

      <el-dialog title="订单审核" :visible.sync="openApprovalForm" class="materialFormDialog" :fullscreen="true">
        <bill-material-approval v-if="openApprovalForm" :order="orderInfo" :material-list="materialList" @approval-success="updateApprovalSuccess">
        </bill-material-approval>
      </el-dialog>

      <el-dialog title="更新后图片" :visible.sync="showUpdateImg" top="5vh" width="80%" @closed="updateImg=''">
        <div style="height:calc(90vh - 54px);overflow:auto;">
          <img :src="formatImgUrl(updateImg)">
        </div>
      </el-dialog>

      <update-order-img v-if="showFrame" :order-id="orderInfo.orderId" @update-success="updateImgSuccess">
      </update-order-img>
    </div>
  `;

  return {
    data: function () {
      var search = {
        factoryNo: '',
        orderId: '',
        companyOrderId: '',
        customerNo: '',
        providerNo: '',
        materialDept: '',
        materialType: ''
      };
      return {
        loading: false,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        searchField: ['materialName', 'materialType', 'model', 'color', 'providerName', 'materialDept', 'orderId', 'companyOrderId', 'factoryNo',
          'customerNo'
        ],
        user: null,
        materialList: [],
        orderInfo: null,
        openMaterialForm: false,
        openApprovalForm: false,
        formDialogTitle: '',
        formMode: '',
        updateMaterial: null,
        showFrame: false,
        showUpdateImg: false,
        updateImg: '',
        materialTypeFilters: [],
        dropdownOption: {
          materialList: [],
          modelList: [],
          colorList: [],
          customerNameList: [],
          unitList: [],
          materialTypeList: []
        },
        warehouseList: {
          "1": "原材料仓",
          "2": "辅料仓"
        },
        pagination: {
          currentPage: 1,
          totalCount: 0,
          pageSize: 1
        }
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      SysUtil.getUser().then(function (user) {
        self.user = user;
        Promise.all([
          self.setMaterialList(true),
          self.setMaterialNameList(),
          self.setModelList(),
          self.setColorList(),
          self.setCustomerNameList(),
          self.setMaterialTypeList(),
          self.setUnitList()
        ]).then(function () {
          self.loading = false;
        });
      });
    },

    methods: {
      setMaterialList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        }

        var search = this.search;
        var postData = _.cloneDeep(search);

        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        postData.start = start;
        postData.length = pageSize;

        var materialDept = postData.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }
        delete postData.materialDept;

        var self = this;
        return ajaxRequest('feedOrder/getOrderInfoDetailByDetail', postData).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }

          var order = _.get(res, 'returnData[0]');
          var orderInfo = null;
          var materialList = [];
          if (!SysUtil.isEmpty(order)) {
            var fields = ['orderId', 'companyOrderId', 'factoryNo', 'customerNo'];
            var myApplyType = order.myApplyType;
            orderInfo = {
              myApplyType: myApplyType,
              isBom: order.isBom,
            };

            var hasApproval = false;
            if (myApplyType === 2) {
              var approvalUserId = order.approvalUserId;
              if (approvalUserId.length > 0) {
                hasApproval = approvalUserId.indexOf(order.applyUserId) !== -1;
              }
            }
            orderInfo.hasApproval = hasApproval;

            for (var i = 0; i < fields.length; i++) {
              var field = fields[i];
              var value = order[field];
              if (SysUtil.isEmpty(value)) {
                value = '';
              } else {
                value = value.trim();
              }
              orderInfo[field] = value;
            }

            materialList = order.orderInfoDetailList;
            materialList = _.map(materialList, function (material) {
              material = new BillMaterialModel(material);
              return material;
            });
            materialList.sort(function (obj1, obj2) {
              var res = obj1.materialType.localeCompare(obj2.materialType);
              if (res !== 0) {
                return res;
              }
              var lineNo1 = Number(obj1.lineNo);
              var lineNo2 = Number(obj2.lineNo);
              return lineNo1 - lineNo2;
            });

            orderInfo.canHandle = order.businessTemplate !== 1;
          }

          var materialTypeFilters = _.map(materialList, function (material) {
            return {
              text: material.materialType,
              value: material.materialType
            };
          });
          materialTypeFilters = _.uniqBy(materialTypeFilters, 'value');
          self.materialTypeFilters = materialTypeFilters;

          self.orderInfo = orderInfo;
          self.materialList = materialList;
          self.pagination.totalCount = res.iTotalRecords;
          return materialList;
        }).catch(function () {
          return [];
        });
      },

      resetMaterialList: function (isSearch) {
        this.loading = true;
        var self = this;
        this.setMaterialList(isSearch).then(function () {
          self.loading = false;
        });
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      setMaterialNameList: function () {
        var self = this;
        return DropdownUtil.getMaterialList().then(function (materialList) {
          self.dropdownOption.materialList = materialList;
        });
      },

      setModelList: function () {
        var self = this;
        return DropdownUtil.getModelList().then(function (modelList) {
          self.dropdownOption.modelList = modelList;
        });
      },

      setColorList: function () {
        var self = this;
        return DropdownUtil.getColorList().then(function (colorList) {
          self.dropdownOption.colorList = colorList;
        });
      },

      setCustomerNameList: function () {
        var self = this;
        return DropdownUtil.getCustomerNameList().then(function (customerNameList) {
          self.dropdownOption.customerNameList = customerNameList;
        });
      },

      setMaterialTypeList: function () {
        var self = this;
        return DropdownUtil.getMaterialTypeList().then(function (materialTypeList) {
          self.dropdownOption.materialTypeList = materialTypeList;
        });
      },

      setUnitList: function () {
        var self = this;
        return DropdownUtil.getUnitList().then(function (unitList) {
          self.dropdownOption.unitList = unitList;
        });
      },

      searchData: function () {
        this.pagination.currentPage = 1;
        this.resetMaterialList(true);
      },

      pageChange: function () {
        this.resetMaterialList();
      },

      addMaterial: function () {
        this.formDialogTitle = '新增物料';
        this.formMode = 'add';
        this.updateMaterial = null;
        this.openMaterialForm = true;
      },

      toUpdateMaterial: function (material) {
        this.formDialogTitle = '修改物料申请';
        this.formMode = 'update';
        this.updateMaterial = material;
        this.openMaterialForm = true;
      },

      saveSuccess: function (mode, isChange) {
        this.openMaterialForm = false;
        var promiseList = [this.setMaterialList()];
        if (isChange) {
          promiseList.pushArray([
            this.setMaterialNameList(),
            this.setModelList(),
            this.setColorList()
          ]);
        }

        this.loading = true;
        var self = this;
        Promise.all(promiseList).then(function () {
          self.loading = false;
        });
      },

      materialDialogClosed: function () {
        this.formDialogTitle = '';
        this.formMode = '';
        this.updateMaterial = null;
      },

      delMaterial: function (material) {
        var self = this;
        var orderInfoDetail = {
          materialType: material.materialType
        };
        var postData = {
          applyOrderInfoDetail: JSON.stringify(orderInfoDetail),
          orderInfoDetailId: material.id,
          type: 'delete'
        };

        var self = this;
        this.$confirm('是否删除该条物料?', '确认删除').then(function () {
          self.loading = true;
          ajaxRequest('feedOrder/deleteOrderInfoDetail', postData).then(function () {
            self.loading = false;
            self.$alert('提交删除物料申请成功', '信息', {
              callback: function () {
                self.resetMaterialList();
              }
            });
          }).catch(function () {
            self.loading = false;
          });
        }).catch(function () {});
      },

      approvalOrder: function () {
        this.openApprovalForm = true;
      },

      updateApprovalSuccess: function () {
        this.openApprovalForm = false;
        this.resetMaterialList();
      },

      updateImage: function () {
        this.showFrame = true;
      },

      updateImgSuccess: function (url) {
        this.showFrame = false;
        this.updateImg = url;
        this.showUpdateImg = true;
      },

      getMaterialTableClassName: function (option) {
        var material = option.row;
        var type = material.type;
        if (type === 3) {
          return 'material-added';
        }
        return;
      },

      tableFilter: function (value, row) {
        var materialType = row.materialType;
        return materialType === value;
      }
    },

    components: {
      CommonSearchForm: CommonSearchForm,
      SearchBtnView: SearchBtnView,
      BillMaterialForm: BillMaterialForm,
      BillMaterialApproval: BillMaterialApproval,
      UpdateOrderImg: UpdateOrderImg
    },

    template: template
  };
}();
